package com.smbms.dao;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {

	// 让工厂类对象唯一存在于内存当中，可以将对象用static修饰 ALT+/
	private static SqlSessionFactory sFactory;
	// 静态代码块去初始化sFactory
	static {

		// 读取配置文件
		// 1.读取全局的配置文件
		String resource = "mybatis-config.xml";
		// 2.获取文件的输入流
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream(resource);

			sFactory = new SqlSessionFactoryBuilder().build(inputStream);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 创建SqlSession
	public static SqlSession createSqlSession() {
		return sFactory.openSession();
	}

	// 关闭SqlSession
	public static void closeSqlsession(SqlSession session) {
		if (session != null) {
			session.close();
		}
	}

}
